package com.czw.controller;


import com.czw.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


@Controller
public class TestController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public String result;

    @RequestMapping(value = "/hello")
    public String index() {
        return "hello";
    }

    @RequestMapping(value = "/insert", method = RequestMethod.POST)
//    @ResponseBody
    public String show(User user, Model model) {
        if(jdbcTemplate.update("INSERT INTO t_user VALUES (?,?,?,?)",user.getId(),user.getName(),user.getAge(),user.getPwd())==1){
            result="success";
        }else {
            result="fail";
        }
        return "show";
    }

    @RequestMapping(value = "/show")
    public String show(Model model){
        String sql="SELECT * from t_user";
        List<User> l= jdbcTemplate.query(sql, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User user=new User();
                user.setId(rs.getInt(1));
                user.setName(rs.getString(2));
                user.setAge(rs.getInt(3));
                return user;
            }
        });
        model.addAttribute("users",l);
        System.out.println(l.size());
        return "show";
    }

    @RequestMapping(value = "/result",method =RequestMethod.POST)
    @ResponseBody
    public String result(){
        return result;
    }
}
